package cn.qicaiwang.open.framework.configuration;

import cn.qicaiwang.open.common.utils.ProvinceContext;
import cn.qicaiwang.open.common.utils.ProvinceUtil;
import cn.qicaiwang.open.common.utils.StringUtils;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Description
 * @Author gaoxi
 * @Date 2022/5/17 9:54 上午
 **/
@Configuration
@MapperScan({"cn.qicaiwang.open.*.mapper", "cn.qicaiwang.crm.mapper", "cn.qicaiwang.crm.*.mapper"})
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 1. 先添加动态表名拦截器（确保优先执行）
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();

        dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {
            // 只处理 enterprise 表
            if ("enterprise".equalsIgnoreCase(tableName)) {
                // 从ThreadLocal获取省份（更可靠的方式）
                String province = ProvinceContext.getProvince();

                // 如果ThreadLocal没有，再从请求中获取（兼容直接调用场景）
                if (StringUtils.isBlank(province) &&
                        RequestContextHolder.getRequestAttributes() != null) {
                    province = ((ServletRequestAttributes) RequestContextHolder
                            .getRequestAttributes())
                            .getRequest().getParameter("province");
                }

                if (StringUtils.isNotBlank(province)) {
                    return "enterprise_" + ProvinceUtil.getProvinceCode(province);
                }
            }
            return tableName;
        });

        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);

        // 2. 后添加分页插件（确保表名替换后再分页）
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        paginationInnerInterceptor.setMaxLimit(1000L); // 设置单页最大记录数
        interceptor.addInnerInterceptor(paginationInnerInterceptor);

        return interceptor;
    }
}

